import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:proj_shop/constant/constant.dart';
import 'package:proj_shop/http/weibo/http_weibo.dart';
import 'package:proj_shop/http/weibo/weibo_service_url.dart';
import 'package:proj_shop/roots/weibo/model/WeiBoListModel.dart';
import 'package:proj_shop/roots/weibo/model/weibo_model.dart';
import 'package:proj_shop/widgets/loading_container.dart';

class WeiBoHomeListPager extends StatefulWidget {
  final String mCatId;

  const WeiBoHomeListPager({Key key, this.mCatId}) : super(key: key);
  @override
  _WeiBoHomeListPagerState createState() => _WeiBoHomeListPagerState();
}

class _WeiBoHomeListPagerState extends State<WeiBoHomeListPager>
    with AutomaticKeepAliveClientMixin {
  bool isRefreshloading = true;
  bool isloadingMore = false; //是否显示加载中
  bool ishasMore = true; //是否还有更多
  num mCurPage = 1;
  ScrollController _scrollController = new ScrollController();
  List<WeiBoModel> hotContentList = [];

  @override
  void initState() {
    // 加载数据
    getSubDataRefresh();
    // 监听滚动
    _scrollController.addListener(() {});
    super.initState();
  }

  @override
  void setState(fn) {
    if (mounted) {
      super.setState(fn);
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: LoadingContainer(
        isLoading: isRefreshloading,
        child: RefreshIndicator(
          child: ListView.builder(
            itemCount: hotContentList.length + 1,
            controller: _scrollController,
            itemBuilder: (_, int index) {
              return ListTile();
            },
          ),
          onRefresh: getSubDataRefresh,
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  Future<void> getSubDataRefresh() async {
    isloadingMore = false;
    ishasMore = true;
    mCurPage = 1;

    FormData formData = FormData.fromMap({
      "catid": widget.mCatId,
      "pageNum": "1",
      "pageSize": Constant.PAGE_SIZE,
      //"userId": UserUtil.getUserInfo().id,
    });

    // 请求微博列表数据
    HttpWeibo().post(
      WeiboServiceUrl.getWeiBo,
      formData,
      (data) {
        WeiBoListModel category = WeiBoListModel.fromJson(data);
        hotContentList.clear();
        hotContentList.addAll(category.data.list);
        setState(() {
          isRefreshloading = false;
        });
      },
      (error) {
        print("接口异常：" + error);
        //  ToastUtil.show(error);
        setState(() {
          isRefreshloading = false;
        });
      },
    );
  }
}
